package com.chendechao.model_home.ui

import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.chendechao.lib_base.BaseFragment
import com.chendechao.model_home.adapter.HomePagerAdapter
import com.chendechao.model_home.databinding.FragmentHomeBinding
import com.chendechao.model_home.ui.hot.HotFragment
import com.chendechao.model_home.ui.movie.MovieFragment
import com.chendechao.model_home.ui.recommend.RecommendFragment
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding,HomeViewModel>(FragmentHomeBinding::inflate) {
    override val viewModel: HomeViewModel by viewModels()
    override fun initView() {
        viewModel.sendEvent(HomeIntent.GetSimpleType)

    }
    private fun getFragment():List<Fragment>{
        return listOf(
            RecommendFragment(),
            MovieFragment(),
            HotFragment()
        )
    }

    override fun initData() {
        collectState(viewModel.state){state ->
            updateUI(state)
        }

    }
    private fun updateUI(state:HomeUIState){
        val fragements = getFragment()
        val tabLayoutName = state.simpleType?.take(3)
        binding.apply {
            val tabLayout = tabLayout
            val viewPage = homeViewPager
            //设置viewPage2的适配器
            val adapter = HomePagerAdapter(this@HomeFragment,fragements)
            viewPage.adapter = adapter
            //将TabLayout和ViewPage2绑定在一起
            TabLayoutMediator(tabLayout,viewPage){tab, position ->
                tab.text = tabLayoutName?.get(position)?.typename
            }.attach()

        }
    }


}